﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SampleDataTools
{
    class ControlDataUpdater<T> where T : class
    {
        public T Parameter { get; set; }
        public int Start { get; set; }
        public Action<double, double, T> Action { get; set; }

        public void Update(Byte[] buff, DataType type)
        {
            if (buff != null)
            {
                Action?.Invoke(
                    GetValue(buff, 0, type), // time
                    GetValue(buff, Start, type), // value
                    Parameter // 
                    );
            }
        }

        public void Update(double time, double value)
        {
            Action?.Invoke(time, value, Parameter);
        }

        private double GetValue(byte[] buff, int index, DataType type)
        {
            double value = 0.0;
            if (buff != null && buff.Length > index * (type == DataType.Double ? 8 : 4))
            {
                value = type == DataType.Double ?
                                BitConverter.ToDouble(buff, index * 8) :
                                BitConverter.ToSingle(buff, index * 4);
            }
            return value;
        }

        internal void Update(BuffData data)
        {
            if (data != null)
            {
                Update(data.GetTime(), data.GetValue(Start));
            }
        }
    }
}
